<template>
	<view class="page-container">
		<!-- 主要内容区 -->
		<u-popup :show="popupShow" mode="center" @close="popupShow=false" round="10">
			<autoCollectionVue />
		</u-popup>
		<view class="main-content">
			<!-- 功能卡片区域 -->
			<view class="feature-grid">
				<!-- 自动归集 -->
				<view class="feature-card" @click="handleCardClick('自动归集')">
					<view class="icon-wrapper auto-bg">
						<u-icon name="setting" color="#fa3534" size="36"></u-icon>
					</view>
					<view class="feature-title">自动归集</view>
					<view class="feature-desc">选择归集方式完成归集</view>
				</view>
				<!-- 扫码归集 -->
				<view class="feature-card" @click="handleCardClick('扫码归集')">
					<view class="icon-wrapper primary-bg">
						<u-icon name="scan" color="#1677ff" size="36"></u-icon>
					</view>
					<view class="feature-title">扫码归集</view>
					<view class="feature-desc">扫描票据上的二维码快速归集</view>
				</view>

				<!-- 手工归集 -->
				<view class="feature-card" @click="handleCardClick('手工归集')">
					<view class="icon-wrapper secondary-bg">
						<u-icon name="edit-pen" color="#36cbcb" size="36"></u-icon>
					</view>
					<view class="feature-title">手工归集</view>
					<view class="feature-desc">手动输入票据信息完成归集</view>
				</view>

				<!-- 导入文件 -->
				<view class="feature-card" @click="handleCardClick('导入文件')">
					<view class="icon-wrapper accent-bg">
						<u-icon name="file-text" color="#ff7d00" size="36"></u-icon>
					</view>
					<view class="feature-title">导入文件</view>
					<view class="feature-desc">导入文件中的票据信息</view>
				</view>
				<!-- 	<view class="flexBox">
					<view class="flexItem" @click="handleCardClick('导入文件')">
						<view class="icon-wrapper accent-bg">
							<u-icon name="plus-circle" color="#ff7d00" size="36"></u-icon>
						</view>
						<view class="feature-title">选择PDF文件</view>
						<view class="feature-desc">批量导入文件中的票据信息</view>
					</view>
					<view class="flexItem">
						<view class="icon-wrapper accent-bg">
							<u-icon name="file-text" color="#ff7d00" size="36"></u-icon>
						</view>
						<view class="feature-title">上传文件</view>
						<view class="feature-desc">批上传文件中的票据信息</view>
					</view>
				</view> -->
			</view>

			<!-- 帮助提示 -->
			<view class="help-section">
				<view class="help-title">
					<u-icon name="info-circle" color="#1677ff" size="20" class="help-icon"></u-icon>
					<text>帮助</text>
				</view>
				<view class="help-list">
					<!-- <view class="help-item">
						<u-icon name="checkmark-circle" color="#1677ff" size="16" class="help-item-icon"></u-icon>
						<text>支持除一般缴款书之外的财政电子票据</text>
					</view> -->
					<view class="help-item">
						<u-icon name="checkmark-circle" color="#1677ff" size="16" class="help-item-icon"></u-icon>
						<!-- <text>导入文件支持PDF、OFD格式</text> -->
						<text>导入文件支持PDF格式</text>
					</view>
				</view>
			</view>
		</view>
		<u-modal ref="editModal" title="提示" :show="showEditModal" :mask-close-able="false" :showCancelButton='true'
			@cancel='showEditModal=false' @confirm="confirm" :close-on-click-modal="false">
			<text>账号未完善，部分功能不可用，是否去完善?</text>
		</u-modal>
	</view>
</template>

<script>
	import autoCollectionVue from './autoCollection.vue';
	import {
		checkEinvoice
	} from '@/api/homeApi.js'
	export default {
		components: {
			autoCollectionVue
		},
		data() {
			return {
				popupShow: false,
				showAutoModal: false,
				showEditModal: false,
				isIdentification: 0,
				fileName: '', // 文件名
				fileBase64: '', // 文件base64编码
			}
		},
		created() {
			this.isIdentification = uni.getStorageSync('isIdentification') || 0
		},
		methods: {
			async confirm() {
				uni.navigateTo({
					url: `/pages/login/login?stepNum=2&telephone=${uni.getStorageSync('account')}`
				})
				this.showEditModal = false;
			},
			confirmAuto() {

			},
			// 返回上一页
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 处理卡片点击
			handleCardClick(title) {
				console.log(`点击了: ${title}`);
				// 这里可以添加页面跳转逻辑
				// 根据不同标题跳转到对应页面
				switch (title) {
					case '自动归集':
						if (this.isIdentification == 0) {
							this.showEditModal = true;
							return;
						}
						this.popupShow = true
						// uni.navigateTo({
						// 	url: `/pages/home/autoCollection`
						// });
						break;
					case '扫码归集':
						uni.scanCode({
							success: (res) => {
								console.log("扫描成功=" + JSON.stringify(res.result));
								let result = '';
								if (res.result.indexOf('?') > 0) {
									result = res.result.substr(res.result.indexOf('?') + 1, res.result.length);
									result = result.replace(/&/g, '#');
									result = result.replace(/=/g, '-');
								} else {
									result = res.result;
								}
								console.log(result)
								uni.navigateTo({
									url: `/pages/home/billdetail?qrCodeParams=${result}`
								});
							},
							fail: (fail) => {
								console.log('fail', fail)
							}
						});
						break;
					case '手工归集':
						uni.navigateTo({
							url: '/pages/home/handmadeCollection'
						});
						break;
					case '导入文件':
						if (this.isIdentification == 0) {
							this.showEditModal = true;
							return;
						}
						this.choosePdf()
						// uni.navigateTo({url: '/pages/import-file/import-file'});
						break;
				}
			},
			// 选择PDF文件
			choosePdf() {
				// 调用UniApp选择文件API
				wx.chooseMessageFile({
					count: 1, // 最多选择1个文件
					type: 'file', // 必须设置为file，否则extensions不生效
					extensions: ['pdf'], // 限制只能选择pdf文件
					success: async (res) => {
						const tempFile = res.tempFiles[0];
						this.fileName = tempFile.name;
						// 校验文件类型（双重保险，防止特殊情况）
						if (!tempFile.name.endsWith('.pdf')) {
							uni.showToast({
								title: '请选择PDF文件',
								icon: 'none'
							});
							return;
						}
						// 检查文件大小（可选，根据需求调整）
						if (tempFile.size > 10 * 1024 * 1024) { // 10MB
							uni.showToast({
								title: '文件大小不能超过10MB',
								icon: 'none'
							});
							this.clearFile();
							return;
						}
						console.log('res', res)
						// 将文件转为base64
						this.convertToBase64(tempFile.path);
					},
					fail: (err) => {
						console.error('选择文件失败:', err);
						uni.showToast({
							title: '选择文件失败',
							icon: 'none'
						});
					}
				});
			},
			// 将文件转为base64
			convertToBase64(filePath) {
				uni.getFileSystemManager().readFile({
					filePath: filePath,
					encoding: 'base64',
					success: (res) => {
						// 保存base64编码（不含data:前缀）
						this.fileBase64 = res.data;
						console.log('===', res.data)
						this.uploadPdf()
					},
					fail: (err) => {
						console.error('文件转base64失败:', err);
						uni.showToast({
							title: '文件处理失败',
							icon: 'none'
						});
						this.clearFile();
					}
				});
			},
			// 清空已选文件
			clearFile() {
				this.fileName = '';
				this.fileBase64 = '';
			},
			async uploadPdf() {
				if (!this.fileBase64) return;
				// 构造请求参数
				uni.showLoading({
					title: '上传中'
				})

				const res = await checkEinvoice({
					eInvoiceLayoutFile: this.fileBase64
				})
				if (res.result == 0) {
					uni.hideLoading()
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
					const params = {
						...res.eInvoice,
						einvoiceCode: res.eInvoice.eInvoiceCode,
						einvoiceNumber: res.eInvoice.eInvoiceNumber,
						payerName: res.eInvoice.payerPartyName,
						agencyName: res.eInvoice.invoicingPartyName,
						isblock: res.isblock,
						isgive: res.isgive||0,
						status: res.reversal.isReversal ? 9 : (res.exchangePaper.isExchangePaper ? 8 :
							1) //9已作废8已换开1正常
					}
					// 跳转到票据详情页
					uni.navigateTo({
						url: '/pages/home/billdetail?loadItem=' + encodeURIComponent(JSON.stringify(params))
					})
					this.clearFile(); // 上传成功后清空
				} else {
					uni.hideLoading()
					this.$u.toast(res.message || '上传失败');
					this.clearFile();
				}
			},
		}
	};
</script>

<style scoped>
	.flexBox {
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 40rpx 20rpx;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
	}

	.flexItem {
		border-radius: 20rpx;
		padding: 0 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.radioBox {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.page-container {
		background-color: #f5f7fa;
		min-height: 100vh;
		font-family: 'Inter', system-ui, sans-serif;
		color: #1d2129;
	}

	.main-content {
		padding: 30rpx 24rpx;
	}

	/* 功能卡片样式 */
	.feature-grid {
		display: grid;
		/* grid-template-columns: 1fr 1fr 1fr; */
		gap: 30rpx;
		margin-bottom: 60rpx;
	}

	.feature-card {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 40rpx 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
	}

	.feature-card:hover {
		transform: translateY(-6rpx);
	}

	.icon-wrapper {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
	}

	.auto-bg {
		background-color: rgba(250, 53, 52, 0.1);
	}

	.primary-bg {
		background-color: rgba(22, 119, 255, 0.1);
	}

	.secondary-bg {
		background-color: rgba(54, 203, 203, 0.1);
	}

	.accent-bg {
		background-color: rgba(255, 125, 0, 0.1);
	}

	.feature-title {
		font-size: 30rpx;
		font-weight: 500;
		margin-bottom: 10rpx;
	}

	.feature-desc {
		font-size: 24rpx;
		color: #888888;
		text-align: center;
	}

	/* 帮助区域样式 */
	.help-section {
		background-color: rgba(22, 119, 255, 0.05);
		border-radius: 20rpx;
		padding: 30rpx;
	}

	.help-title {
		font-size: 28rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.help-icon {
		margin-right: 15rpx;
	}

	.help-list {
		font-size: 26rpx;
		color: #666666;
	}

	.help-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.help-item:last-child {
		margin-bottom: 0;
	}

	.help-item-icon {
		margin-right: 15rpx;
		margin-top: 5rpx;
	}

	/* 点击效果 */
	.opacity-70 {
		opacity: 0.7;
	}
</style>